package com.pioneer.fationservice.serviceinfos;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.pioneer.fationservice.R;
import com.pioneer.fationservice.adapters.DoclstInfoAdapter;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.entries.DoclstInfoEntry;
import com.pioneer.fationservice.helpers.ImageHelper;
import com.pioneer.fationservice.helpers.PhoneHelper;
import com.pioneer.fationservice.models.DoclstInfoModel;
import com.pioneer.fationservice.parsers.DoclstInfoParser;

/**
 * 
 * @author Mrper
 *
 */
public class DocListActivity extends FinalActivity implements OnItemClickListener{
		
	@ViewInject(id=R.id.layout_actionbar_txtTitle) 
	private TextView txtTitle;//标题栏
	@ViewInject(id=R.id.activity_doclst_imgBack,click="onBackClick") 
	private ImageView imgBack;//返回操作
	@ViewInject(id=R.id.activity_doclst_imgLogo) 
	ImageView imgLogo;//显示图LOGO
	@ViewInject(id=R.id.activity_doclist_plLst,click="onTitleClick") 
	private PullToRefreshListView plLst;//刷新列表控件
	private ProgressDialog dialog;//进度提示条
	
	private int flag = 0,//文档类型
				pageIndex = 0;//当前页码
	private List<DoclstInfoEntry> doclst = new ArrayList<DoclstInfoEntry>();//文档列表集合
	private DoclstInfoAdapter doclstAdapter;//文档列表数据适配器
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_doclist);
		initActivity();//初始化activity
		initCtls();//初始化控件
		adjustLogoImage();//调整图片
		requestDoclstInfo(1,true,true);//请求知识小文档列表
	}
	
	
	/**
	 * 调整LOGO图片
	 */
	public void adjustLogoImage(){
		Bitmap bmpOrg = ((BitmapDrawable)this.getResources()
				.getDrawable(R.drawable.ic_doclst_logo)).getBitmap();
		imgLogo.setImageBitmap(ImageHelper.scaleBitmap(bmpOrg, 
				PhoneHelper.getScreenInfo(this).widthPixels));
	}
	
	/**
	 * 初始化activity
	 */
	public void initActivity(){
		Intent intent = getIntent();
		if(intent!=null && intent.hasExtra("flag")){
			flag = intent.getIntExtra("flag", 0);
			switch(flag){
			case 1:
				txtTitle.setText("行车安全");
				break;
			case 2:
				txtTitle.setText("汽车小知识");
				break;
			case 3:
				txtTitle.setText("故障应急");
				break;
			}
		}
	}
	
	/**
	 * 初始化控件
	 */
	public void initCtls(){
		plLst.setMode(Mode.BOTH);//可上拉、下啦
		plLst.setOnRefreshListener(new OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				requestDoclstInfo(1,false,true);
			}
			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				requestDoclstInfo(pageIndex+1,false,false);
			}
		});
		doclstAdapter = new DoclstInfoAdapter(this, doclst);
		plLst.setOnItemClickListener(this);
		plLst.setAdapter(doclstAdapter);
	}
	
	/**
	 * 清空文档列表
	 */
	public void clearDoclst(){
		doclst.clear();
		doclstAdapter.notifyDataSetChanged();
	}
	

	/**
	 * 列表项点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		Intent intent = new Intent(this,DocDetailActivity.class);
		final DoclstInfoEntry item = doclst.get(position-1);
		intent.putExtra("flag", flag);
		intent.putExtra("doc_id", item.docId);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}
	
	/**
	 * 返回操作
	 * @param view
	 */
	public void onBackClick(View view){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
	}
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
    		imgBack.performClick();//模拟点击返回按钮
    		return true;
    	}
    	return super.onKeyDown(keyCode, event);
    }
	
    /**
     * 请求只是小文档列表集合
     * @param shopId
     */
    public void requestDoclstInfo(final int pageIndex,final boolean isFirstQuery,final boolean isClearlst){
		if(isFirstQuery) dialog = ProgressDialog.show(this, "", "请稍等...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("f", String.valueOf(flag));
    	params.put("p", String.valueOf(pageIndex));
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_DOC_LIST, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			if(plLst.isRefreshing())plLst.onRefreshComplete();
    			Toast.makeText(DocListActivity.this, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			if(plLst.isRefreshing())plLst.onRefreshComplete();
    			System.out.println("小知识文档列表信息----返回信息："+str);
    			DoclstInfoModel model = new DoclstInfoParser(str).getResponseObject();
    			switch(model.status){
    			case 1:
    				if(isClearlst) clearDoclst();
    				doclst.addAll(model.doclst);
    				doclstAdapter.notifyDataSetChanged();
    				DocListActivity.this.pageIndex = pageIndex;
    				break;
    			case 0:
    				Toast.makeText(DocListActivity.this, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
    		}
    	});
	}

    
}
